package input.pilot;

import java.util.logging.Logger;

import settings.ControlSettings;
import logic.ships.hunter.Hunter;

import com.jme.input.MouseInput;
import com.jme.math.Vector3f;
import com.jme.scene.CameraNode;
import com.jme.scene.Controller;
import com.jme.system.DisplaySystem;

import fileHandling.language.options.OptionValues;

public class CameraNodeController extends Controller {
	
	public static final Logger logger = Logger.getLogger("input.pilot.CameraNodeController");
	
	private static final long serialVersionUID = 1L;
	
	public static final Vector3f DEFAULT_CAM_NODE_LOCATION = new Vector3f(0f, 3f, -9.0f);
	public static final Vector3f MAX_SPEED_DIR = new Vector3f(0f, 0f, -2f);
	
	private DisplaySystem display;
	private Hunter hunter;
	
	private CameraNode camNode;
	private MouseInput mouseInput;
	
	public CameraNodeController(Hunter hunter, CameraNode camNode) {
		this.hunter = hunter;
		this.camNode = camNode;
		
		display = DisplaySystem.getDisplaySystem();
		mouseInput = MouseInput.get();
	}
	
	@Override
	public void update(float time) {
		float speedFactor = hunter.getCurrentEngineSpeed() / hunter.getMaxBoostSpeed();
		Vector3f speedDir = MAX_SPEED_DIR.mult(speedFactor);
		
		if(!mouseButtonDown()) {
			moveTo(camNode, speedDir, time * 2f);
			return;
		}
		
		int mouseX = mouseInput.getXAbsolute();
		int mouseY = mouseInput.getYAbsolute();
		
		Vector3f screenCenter = new Vector3f(display.getWidth() / 2f, display.getHeight() / 2f, 0f);
		Vector3f mousePos = new Vector3f(mouseX, mouseY, 0f);
		Vector3f dir = mousePos.subtract(screenCenter);
		float amount = dir.length() * 0.01f;
		dir.normalizeLocal().multLocal(2.7f);
		dir.x = -dir.x;
		dir.addLocal(speedDir);
		
		moveTo(camNode, dir, time * amount);
	}
	
	protected boolean mouseButtonDown() {
		int index = 0;
		OptionValues mouseValue = ControlSettings.get().getLookAround();
		switch(mouseValue) {
			case Left_Mouse_Button: index = 0; break;
			case Right_Mouse_Button: index = 1; break;
			case Middle_Mouse_Button: index = 2; break;
		}
		
		return mouseInput.isButtonDown(index);
	}
	
	protected void moveTo(CameraNode camNode, Vector3f dir, float amount) {
		if(dir == null || amount == 0f) return;
		
		Vector3f newLoc = DEFAULT_CAM_NODE_LOCATION.add(dir);
		
		camNode.getLocalTranslation().interpolate(newLoc, amount);
	}
	
	public void changeHunter(Hunter hunter) {
		this.hunter = hunter;
	}
}